package com.scedu.spring5.config;

import com.alibaba.druid.pool.DruidDataSource;

import org.springframework.context.annotation.Bean;
import org.springframework.context.annotation.ComponentScan;
import org.springframework.context.annotation.Configuration;
import org.springframework.jdbc.core.JdbcTemplate;
import org.springframework.jdbc.datasource.DataSourceTransactionManager;
import org.springframework.transaction.annotation.EnableTransactionManagement;

import javax.sql.DataSource;


//@Configuration //配置类
@ComponentScan(basePackages = "com.scedu.spring5") //开启组件扫描
@EnableTransactionManagement //开启事务注解
public class TxConfig {
    @Bean //配置druid连接池
    public DruidDataSource getDruidDataSource(){
        DruidDataSource druidDataSource=new DruidDataSource();
        druidDataSource.setUsername("root");
        druidDataSource.setPassword("123");
        druidDataSource.setUrl("jdbc:mysql://172.18.42.8:3306/book_db");
        druidDataSource.setDriverClassName("com.mysql.cj.jdbc.Driver");
        return druidDataSource;
    }

    //配置JDBC Template对象
    @Bean  //因为DruidDataSource已经被IOC注入了，所以Spring会直接按类型查找到她
    public JdbcTemplate setJdbcTemplate(DataSource druidDataSource){
        JdbcTemplate jdbcTemplate=new JdbcTemplate();
        // jdbcTemplate.setDataSource(getDruidDataSource()); //这样写会注入两次
        jdbcTemplate.setDataSource(druidDataSource); //这样写才最
        return jdbcTemplate;
    }

    //创建事务管理器
    @Bean //因为DruidDataSource已经被IOC注入了，所以Spring会直接按类型查找到她
    public DataSourceTransactionManager setDataSourceTransactionManager(DataSource druidDataSource){
        DataSourceTransactionManager dataSourceTransactionManager=new DataSourceTransactionManager();
        dataSourceTransactionManager.setDataSource(druidDataSource);
        return  dataSourceTransactionManager;
    }
}
